/* eslint-disable */

/*
* 剩余开发功能
* 1：兼容的响应式监听（已完成es6，不兼容ie）
* 2：一些钩子函数
* 3：增强defaultOption的混入功能
* 4：对mixin的优化
* */
import {EleResize, auxiliary} from './util'

const {type, deepCopy, depthMerger, depthMergers} = auxiliary

let _Echerts

//初始化echart
function initEchart(deploy) {
    _Echerts = deploy.echart
}


class mainEchart {
    dom

    chart

    mixin = []
    isCopyFill //是否填充
    CopyFills
    _dom

    //新增中
    option // 实例化补充配置
    defaultOption = {} // 默认配置
    insertOption = {}
    pluginsOptions = {} // 插件式的option合并结果
    defaultPluginsOption = {} // defaultOption 和 pluginsOptions 的合并结果
    resolveOption = {} // defaultPluginsOption 与实例化补充 option 的合并结果
    presentOption = {} // 当前状态的 option

    constructor(option) {
        this.examine('constructor', option)
        this.dom = option.dom
        this.option = option.options

        if (option.isCopyFill) {
            this.isCopyFill = option.isCopyFill
        }
        //默认值
        if (option.mixin) {
            this.mixin = [...this.mixin, ...option.mixin]
        }

    }

    // 初始化数据
    init() {
        this.initPluginsOption()
        this.initDefaultOption()
        this.initOption()
        return this
    }

    // 初始化最终配置项
    initOption() {
        console.log('before init option')
        if (this.isCopyFill === true) {
            // 开启数据复用
            let defaultKeys = Object.keys(this.defaultPluginsOption),
                optionsKeys = Object.keys(this.option)
            defaultKeys.forEach(key => {
                if (
                    this.optionReset(key)
                    && this.defaultPluginsOption[key].length === 1
                    && type(this.option[key]) === 'array'
                    && this.option[key].length > 1
                ) {
                    let optionItem = this.defaultPluginsOption[key][0]
                    for (let i = 0; i < this.option[key].length - 1; i++) {
                        this.defaultPluginsOption[key].push(optionItem)
                    }
                }
            })
        }
        this.resolveOption = depthMerger(this.defaultPluginsOption, this.pretreatment(this.option))
        this.presentOption = this.resolveOption
        console.log('after init option')
    }

    // 初始化插件数据
    initPluginsOption() {
        console.log('before init PluginsOption')
        if (type(this.mixin) === 'array' && this.mixin.length > 0) {
            this.pluginsOptions = depthMergers((acc, cut) => {
                return this.pretreatment(cut)
            }, ...this.mixin)
        }
        this.presentOption = this.pluginsOptions
        console.log('after init PluginsOption')
    }

    //初始化默认数据与插件数据
    initDefaultOption() {
        console.log('before init default')
        this.defaultPluginsOption = this.pretreatment(
            depthMerger(this.defaultOption, this.pluginsOptions)
        )
        this.presentOption = this.defaultPluginsOption
        console.log('after init default')
    }

    // 初始化dom，chart
    disposeDom() {
        let dom = null
        if (typeof this.dom === 'string') {
            dom = document.querySelectorAll(this.dom)
            if (dom.length > 1) {
                throw new Error('The length of the dom is greater than 1')
            }
            dom = dom[0]
            this.chart = _Echerts.init(dom)
            this._dom = dom
        } else {
            dom = this.dom
            this.chart = _Echerts.init(dom)
            this._dom = dom
        }
        setTimeout(() => {
            EleResize.on(dom, () => {
                this.chart.resize();
            });
        })
    }

    //渲染函数
    render() {
        // this.disposeDefaultOption()
        // this.disposeOption()
        this.setOption()
        return this
    }

    //启动渲染
    setOption() {
        if (typeof this.chart === 'undefined') {
            this.disposeDom()
        }
        this.chart.setOption(this.resolveOption)
        return this
    }

    //改变数据
    data(category) {
        if (type(category) === 'object') {
            // console.log(this.resolveOption)
            Object.keys(category).forEach((key, index) => {
                let dataType = 'data'
                if (key === 'title') {
                    dataType = 'text'
                }
                if (type(this.resolveOption[key]) === 'array') {
                    if (category[key].some(item => type(item) === 'array')
                        && category[key].length > 1
                        && this.resolveOption[key].length >= category[key].length
                    ) {
                        for (let i = 0; i < this.resolveOption[key].length; i++) {
                            this.resolveOption[key][i][dataType] = category[key][i]
                        }
                    } else {
                        this.resolveOption[key][dataType] = category[key]
                    }

                } else {
                    this.resolveOption[key][dataType] = category[key]
                }
            })
        } else {
            if (type(this.resolveOption['series']) === 'array') {
                for (let i = 0; i < this.resolveOption['series'].length; i++) {
                    this.resolveOption['series'][i].data = category[i]
                }
            } else {
                this.resolveOption['series'].data = category
            }
        }
        return this
    }

    // 判断是否是需要修正结构的key值
    optionReset(type) {
        const optionResetList = [
            "title",
            "legend",
            "geo",
            "grid",
            "xAxis",
            "yAxis",
            "dataZoom",
            "visualMap",
            "series",
        ]
        return optionResetList.includes(type)
    }

    //修正options 的配置结构
    pretreatment(option) {
        option = deepCopy(option)
        for (let key in option) {
            if (Object.prototype.hasOwnProperty.call(option, key)) {
                if (this.optionReset(key) && !Array.isArray(option[key])) {
                    option[key] = [option[key]];
                }
            }
        }
        return option
    }

    //判断option参数
    examine(type, option) {
        if (type === "constructor") {
            if (!Object.keys(option).includes('dom')) {
                throw Error("dom is undefined:")
            }
        }
    }

}

class createEchart extends mainEchart {
    defaultOption = {
        legend: [
            {
                icon: "circle",
                textStyle: {
                    color: "#fff",
                },
            },
        ],
        tooltip: {
            show: true,
            backgroundColor: "rgba(0,0,0,.51)",
            borderWidth: 0,
            padding: 20,
        },
        xAxis: [
            {
                type: "category",
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    color: "#F0F0F0",
                },
                splitLine: {
                    lineStyle: {
                        color: "rgba(238,238,238, .1)",
                    },
                },
                boundaryGap: true,
            },
        ],
        yAxis: [
            {
                type: "value",
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    color: "red",
                },
                nameTextStyle: {
                    color: "#F0F0F0",
                },
                splitLine: {
                    lineStyle: {
                        color: "rgba(238,238,238, .1)",
                    },
                },
                splitNumber: 3,
            },
            {
                type: "value",
                axisLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLabel: {
                    color: "#F0F0F0",
                },
                splitLine: {
                    show: false,
                },
                nameTextStyle: {
                    color: "#F0F0F0",
                },
                splitNumber: 3,
            },
        ],
        grid: [
            {
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                containLabel: true,
            },
        ],
    }

    constructor(option) {
        super({...option, isCopyFill: true})
        this.init()
    }
}

export {initEchart, createEchart, mainEchart, _Echerts}